<?php

namespace App\Http\Controllers\Admin\Goods;

use App\B2BProject\Admin\AdminControllerBuildTrait;
use App\B2BProject\Custom\Business\Goods;
use App\B2BProject\Custom\Business\GoodsCategory;
use App\B2BProject\Custom\Business\Store;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    use AdminControllerBuildTrait;

    protected $moduleName = '';

    /**
     *
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $tab = $request->query('tab');

            $pageSize = $request->query('pageSize', 7);

            $goods = Goods::orderBy('created_at', 'desc');

            $body = [];

            // 判断是否要求返回指定的 TAB
            if ($tab == -1) {
                // 由于该页面只有一个特殊的 TAB ，因此不需要再做 TAB ID 的判断
                // 但是如果在其他类似页面存在大于 2 个 TAB 的情况，且需要返回特别 TAB 的可做独立判断
                // 如 if ($tab == ??) 这种，以上。
                $body[] = $this->getList(0, clone $goods, $pageSize);
                $body[] = $this->getList(1, clone $goods, $pageSize);
            } else {
                $body[] = $this->getList($tab, $goods, $pageSize);
            }

            return response()->json(['data' => $body, 'tab' => $tab]);
        }

        return view('admin/goods/goods/index');

    }

    protected function getList($type, $query, $pageSize)
    {
        if ($type == 0) {

            if ($storeName = \Request::query('storeName')) {
                $query->whereHas('store.member.information', function ($query) use ($storeName) {
                    $query->where('company', 'like', "%$storeName%");
                });
            }

            if ($brandName = \Request::query('brandName')) {
                $query->whereHas('brand', function ($query) use ($brandName) {
                    $query->where('name', 'like', "%$brandName%");
                });
            }

            if ($goodName = \Request::query('goodName')) {
                $query = $query->where('name', 'like', "%$goodName%");
            }

            if ($goodProp = \Request::query('goodProp')) {

                if (\Request::query('goodProp') == 1) {  //  0是自由集散   1是供采分销
                    $query = $query->where('grant_status', 1);
                } else {
                    $query = $query->where('grant_status', 0);
                }
            }

            if(\Request::query('state')){

                if (\Request::query('state') == 1) {
                    $query = $query->where('strict_lock', 0);
                }
                else{
                    $query = $query->where('strict_lock', 1);
                }
            }

            if ($classify_1 = \Request::query('classify_0')) {    //大分类
                $query = $query->where('class_id', $classify_1);
            }

            if ($classify_2 = \Request::query('classify_1')) {    //小分类
                $query = $query->where('category_id', $classify_2);
            }
            $collection = $query->paginate($pageSize);
        } else {

            if ($storeName = \Request::query('storeName')) {
                $query->whereHas('store.member.information', function ($query) use ($storeName) {
                    $query->where('company', 'like', "%$storeName%");
                });
            }

            if ($brandName = \Request::query('brandName')) {
                $query->whereHas('brand', function ($query) use ($brandName) {
                    $query->where('name', 'like', "%$brandName%");
                });
            }

            if(\Request::query('state')){

                if (\Request::query('state') == 1) {
                    $query = $query->where('strict_lock', 0);
                }
                else{
                    $query = $query->where('strict_lock', 1);
                }
            }

            if (\Request::query('state') == 1) {
                $query = $query->where('strict_lock', 0);
            }
           else if (\Request::query('state') == 0) {
                $query = $query->where('strict_lock', 1);
            }else{

           }

            if ($classify_1 = \Request::query('classify_0')) {    //大分类
                $query = $query->where('class_id', $classify_1);
            }

            if ($classify_2 = \Request::query('classify_1')) {    //小分类
                $query = $query->where('category_id', $classify_2);
            }

            $collection = $query->where('strict_lock', true)->paginate($pageSize);
        }

        $list = $this->listProcessHandler($collection);

        return [
            'detail'         => $list,
            'pagingConfData' => [
                'page'     => $collection->currentPage(),
                'pageSize' => $pageSize,
                'total'    => $collection->total(),
            ]
        ];
    }

    protected function listProcessHandler($collection)
    {
        $list = [];
        foreach ($collection as $goods) {
            $list[] = [
                'id'            => $goods->id,
                'goodsname'     => $goods->name,
                'storename'     => $goods->store->member?$goods->store->member->information->company:'',
                'brand'         => $goods->brand->name,
                'classify'      => $goods->classCategory->name,
                'price'         => $goods->original_price,
                'stock'         => $goods->stock,
                'detail_href'   => route('goods.detail', ['id' => $goods->id]),
                'imgurl'        => $goods->cover(),
                'goodsproperty' => $goods->grant_status,
                'operate'         =>$goods->strict_lock,
                'state'         =>$goods->strict_lock?'违规下架':'出售中',
                'update_href'         =>route('admin.goods.manage.update',[$goods->id,'operate'=>$goods->strict_lock]),
            ];
        }
        return $list;
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if($request->input('operate')){
            $data=[
                'strict_lock'=>0,
            ];
        }else{
            $data=[
                'strict_lock'=>1,
            ];
        }
        $good = Goods::findOrFail($id);
        $good->update($data);

        return $this->index($request);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 批量删除  循环遍历id进行删除   暂时没用
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function batchRemove(Request $request)
    {
        try {
            return \DB::transaction(function () use ($request) {
                $arr = $request->input('ids');
                foreach ($arr as $good_id) {
                    $good = Goods::findOrFail($good_id);
                    $good->delete();
                }
                return $this->index($request);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }

    /**
     * 批量下架  循环遍历id进行下架
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function unShelve(Request $request)
    {
        try {
            return \DB::transaction(function () use ($request) {
                $arr = $request->input('ids');
                foreach ($arr as $good_id) {  //该值若为 TRUE 表示商品被违禁下架',
                    $data = [
                        'strict_lock' => 1,
                    ];
                    $good = Goods::findOrFail($good_id);
                    $good->update($data);
                }
                return $this->index($request);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }

    }

    /**
     * 批量上架  循环遍历id进行上架
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function shelve(Request $request)
    {
        try {
            return \DB::transaction(function () use ($request) {
                $arr = $request->input('ids');
                foreach ($arr as $good_id) {  //该值若为 TRUE 表示商品被违禁下架',
                    $data = [
                        'strict_lock' => 0,
                    ];
                    $good = Goods::findOrFail($good_id);
                    $good->update($data);
                }
                return $this->index($request);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }


}
